import json

import pymongo
from sqlalchemy import Column, Integer, String, create_engine, Date, Text, Numeric, DateTime
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
import config

engine = create_engine('mysql+pymysql://%s:%s@%s/%s?charset=utf8' % (
    config.MYSQL_USER,
    config.MYSQL_PASSWORD,
    config.MYSQL_HOST,
    config.MYSQL_DB,
), encoding='utf-8')
Session = sessionmaker(bind=engine)

Base = declarative_base()


class Company(Base):
    __tablename__ = 'companies'
    id = Column(Integer, primary_key=True, autoincrement=True)
    # 注册资本(万)
    register_capital = Column(Numeric)
    # 法定代表人
    representative = Column(String(50))
    # 成立日期
    establish_date = Column(Date)
    # 经营范围
    business_scope = Column(Text)
    # 公司名称
    company_name = Column(String(100))
    # 住所（公司地址）
    company_address = Column(String(100))
    # 统一社会信用代码
    credit_code = Column(String(100), index=True, unique=True)
    # 更新时间
    update_ts = Column(Numeric)


def _gen_tuple(self):
    def convert_datetime(value):
        if value:
            return value.strftime("%Y-%m-%d %H:%M:%S")
        else:
            return ""

    for col in self.__table__.columns:
        if isinstance(col.type, DateTime):
            value = convert_datetime(getattr(self, col.name))
        elif isinstance(col.type, Date):
            value = convert_datetime(getattr(self, col.name))
        elif isinstance(col.type, Numeric):
            value = float(getattr(self, col.name)) if getattr(self, col.name) is not None else None
        else:
            value = getattr(self, col.name)
        yield (col.name, value)


def to_dict(self):
    return dict(self._gen_tuple())


def to_json(self):
    return json.dumps(self.to_dict())

Base._gen_tuple = _gen_tuple
Base.to_dict = to_dict
Base.to_json = to_json
Base.metadata.create_all(engine)
